<script setup lang="ts">
import mapboxgl from "mapbox-gl/dist/mapbox-gl.js";
import "mapbox-gl/dist/mapbox-gl.css";
import type { Map, Style } from "mapbox-gl";
import { onMounted, ref, onUnmounted } from "vue";
import { chengdeGeoJSON } from "@/utils/geoJson";
import chengde from "@/utils/cds_new.json";
import testJson from "@/jsonData/test.json";

// 地图配置
const mapConfig: {
  token: string;
  center: [number, number];
  zoom: number;
  minZoom: number;
  maxZoom: number;
  pitch: number; // 俯仰角度
  bearing: number; // 方位角度
} = {
  token:
    "pk.eyJ1IjoiY2hlbndlaWthbmciLCJhIjoiY21laHdwYXM1MGQxYzJscXRqdWJnbXdwMyJ9.FmHbtWPZEO3NrJvyKeTRag",
  center: [109.2274, 34.2307],
  zoom: 6,
  minZoom: 3,
  maxZoom: 18,
  pitch: 10, // 添加俯仰角度，范围 0-85
  bearing: 0, // 添加方位角度，范围 0-360
};

// 自定义高德地图样式
const gaode: Style = {
  version: 8,
  sources: {
    "raster-tiles": {
      type: "raster",
      // tiles: [
      //   "http://webst04.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=6&x={x}&y={y}&z={z}",
      // ],
      tiles: [
        // 使用卫星地图底图
        "http://webst04.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=6&x={x}&y={y}&z={z}",
      ],
      tileSize: 256,
    },
    "raster-annotation": {
      type: "raster",
      // tiles: [
      //   "http://webst02.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=8",
      // ],
      tiles: [
        // 标注层
        "http://webst02.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=8",
      ],
      tileSize: 256,
    },
  },
  layers: [
    {
      id: "simple-tiles",
      type: "raster",
      source: "raster-tiles",
      minzoom: 0,
      maxzoom: 22,
      paint: {
        "raster-opacity": 1, // 恢复卫星图层完全不透明
      },
    },
    {
      id: "simple-annotation",
      type: "raster",
      source: "raster-annotation",
      minzoom: 0,
      maxzoom: 22,
      paint: {
        "raster-opacity": 0.8, // 保持标注清晰可见
      },
    },
  ],
};

const mapRef = ref<HTMLElement | null>(null);
const map = ref<Map | null>(null);

// 初始化地图
const initMap = () => {
  if (!mapRef.value) {
    console.error("地图容器不存在");
    return;
  }

  try {
    mapboxgl.accessToken = mapConfig.token;

    map.value = new mapboxgl.Map({
      container: mapRef.value,
      style: gaode,
      center: mapConfig.center,
      zoom: mapConfig.zoom,
      minZoom: mapConfig.minZoom,
      maxZoom: mapConfig.maxZoom,
      pitch: mapConfig.pitch, // 添加俯仰角度
      bearing: mapConfig.bearing, // 添加方位角度
      attributionControl: false, // 移除默认的属性控件
      dragRotate: true, // 启用鼠标拖动旋转
      touchZoomRotate: true, // 启用触摸缩放和旋转
      pitchWithRotate: true, // 允许通过旋转手势改变俯仰角度
    });

    // 确保启用地图旋转功能
    map.value.dragRotate.enable();
    map.value.touchZoomRotate.enable();

    // 添加导航控件，包含指南针
    const nav = new mapboxgl.NavigationControl({
      visualizePitch: true, // 启用俯仰角度可视化
      showCompass: true, // 显示指南针
    });
    map.value.addControl(nav, "top-right");

    // 监听地图加载完成事件
    map.value.on("load", () => {
      console.log("地图加载完成");

      // 添加承德市边界数据源
      map.value?.addSource("chengde-boundary", {
        type: "geojson",
        data: chengde,
      });

      // 添加边界线图层
      map.value?.addLayer({
        id: "chengde-boundary-line",
        type: "line",
        source: "chengde-boundary",
        paint: {
          "line-color": "#ffffff", // 改为白色边界线，在卫星图上更显眼
          "line-width": 2,
          "line-opacity": 0.8,
        },
      });

      // 添加边界面图层 :TODO 绘制图层
      map.value?.addLayer({
        id: "chengde-boundary-fill",
        type: "fill",
        source: "chengde-boundary",
        paint: {
          "fill-color": "#ffffff", // 改为白色填充
          "fill-opacity": 0.05, // 保持较低的填充透明度
        },
      });

      // 处理线路数据并添加到地图
      const feederLines = testJson.data.map((item: any) => {
        const coordinates = item.feederCoordinate.map((segment: number[][]) => {
          // 将墨卡托坐标转换为经纬度坐标
          return segment.map((point: number[]) => {
            // 墨卡托坐标转经纬度的简化转换
            const lng = (point[0] / 20037508.34) * 180;
            const lat = (point[1] / 20037508.34) * 180;
            const latRad = Math.atan(Math.exp(lat * (Math.PI / 180))) * 2 - Math.PI / 2;
            return [lng, latRad * (180 / Math.PI)];
          });
        });
        
        return {
          type: "Feature",
          properties: {
            feederId: item.feederId,
            feederType: item.feederType
          },
          geometry: {
            type: "MultiLineString",
            coordinates: coordinates
          }
        };
      });

      // 创建线路数据的GeoJSON
      const feederGeoJSON = {
        type: "FeatureCollection",
        features: feederLines
      };

      // 添加线路数据源
      map.value?.addSource("feeder-lines", {
        type: "geojson",
        data: feederGeoJSON,
      });

      // 添加线路图层
      map.value?.addLayer({
        id: "feeder-lines-layer",
        type: "line",
        source: "feeder-lines",
        paint: {
          "line-color": "#ffffff", // 白色线路
          "line-width": 2,
          "line-opacity": 0.8,
        },
      });

      // 将视图定位到承德市
      map.value?.flyTo({
        center: [117.933, 40.992], // 承德市中心点坐标
        zoom: 8,
        essential: true,
      });
    });

    // 监听地图错误事件
    map.value.on("error", (e) => {
      console.error("地图加载错误:", e);
    });
  } catch (error) {
    console.error("初始化地图失败:", error);
  }
};

onMounted(() => {
  initMap();
});

// 组件销毁时清理地图实例
onUnmounted(() => {
  if (map.value) {
    map.value.remove();
    map.value = null;
  }
});
</script>

<template>
  <div class="wrap">
    <div id="map" ref="mapRef" class="map"></div>
  </div>
</template>

<style scoped lang="less">
.wrap {
  width: 100%;
  height: 100%;
  border: 1px solid hotpink;
  .map {
    width: 100%;
    height: 100%;
  }
}
</style>
